package com.ruoyi.evaluate.infoprojectevaluate.controller;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.evaluate.infoprojectevaluate.domain.InfoProjectEvaluate;
import com.ruoyi.evaluate.infoprojectevaluate.service.IInfoProjectEvaluateService;
import com.ruoyi.evaluate.infoprojectevaluate.vo.ProjectEvaluateDetailVo;
import com.ruoyi.evaluate.infoprojectevaluate.vo.ProjectEvaluateExamineVo;
import com.ruoyi.evaluate.infoprojectevaluateindex.domain.InfoProjectEvaluateIndex;
import com.ruoyi.evaluate.infoprojectevaluateindex.service.IInfoProjectEvaluateIndexService;
import com.ruoyi.system.service.ISysRoleService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * 项目评价Controller
 *
 * @author ruoyi
 * @date 2022-02-21
 */
@RestController
@RequestMapping("/infoProjectEvaluate/infoProjectEvaluate")
public class InfoProjectEvaluateController extends BaseController {
    @Autowired
    private IInfoProjectEvaluateService infoProjectEvaluateService;
    @Autowired
    private IInfoProjectEvaluateIndexService infoProjectEvaluateIndexService;
    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 主管处室 查询项目评价列表
     */
    @PreAuthorize("@ss.hasPermi('infoProjectEvaluate:infoProjectEvaluate:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoProjectEvaluate infoProjectEvaluate) {
        Long userId = SecurityUtils.getUserId();
        List<SysRole> roles = sysRoleService.selectRolesByUserIdList(userId);
        Optional.ofNullable(roles).orElseThrow(() -> new RuntimeException("该登录用户没有角色信息！"));
        List<String> rileKeys = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        if (rileKeys.contains("sjc")) {
            //查询创建该项目部门所有信息
            infoProjectEvaluate.setDeptId(SecurityUtils.getDeptId());
            startPage();
            List<InfoProjectEvaluate> list = infoProjectEvaluateService.selectInfoProjectEvaluateList(infoProjectEvaluate);
            return getDataTable(list);
        } else {
            //只查询department_id等于当前登录人的处室Id
            infoProjectEvaluate.setDepartmentId(SecurityUtils.getDeptId());
            startPage();
            List<InfoProjectEvaluate> list = infoProjectEvaluateService.selectInfoProjectEvaluateList(infoProjectEvaluate);
            return getDataTable(list);
        }


    }

    /**
     * 预算单位 查询项目评价列表
     */
    @PreAuthorize("@ss.hasPermi('infoProjectEvaluate:infoProjectEvaluate:list')")
    @GetMapping("/budgetUnitList")
    public TableDataInfo budgetUnitList(InfoProjectEvaluate infoProjectEvaluate) {
        //只查询release_department_id等于当前登录人的处室Id
        infoProjectEvaluate.setReleaseDepartmentId(SecurityUtils.getDeptId());
        startPage();
        List<InfoProjectEvaluate> list = infoProjectEvaluateService.selectInfoProjectEvaluateBudgetUnitList(infoProjectEvaluate);
        return getDataTable(list);
    }

    /**
     * 导出项目评价列表
     */
    @PreAuthorize("@ss.hasPermi('infoProjectEvaluate:infoProjectEvaluate:export')")
    @Log(title = "项目评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoProjectEvaluate infoProjectEvaluate) {
        List<InfoProjectEvaluate> list = infoProjectEvaluateService.selectInfoProjectEvaluateList(infoProjectEvaluate);
        ExcelUtil<InfoProjectEvaluate> util = new ExcelUtil<InfoProjectEvaluate>(InfoProjectEvaluate.class);
        util.exportExcel(response, list, "项目评价数据");
    }

    /**
     * 获取项目评价详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(infoProjectEvaluateService.selectInfoProjectEvaluateById(id));
    }

    /**
     * 新增项目评价
     */
    @PreAuthorize("@ss.hasPermi('infoProjectEvaluate:infoProjectEvaluate:add')")
    @Log(title = "项目评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoProjectEvaluate infoProjectEvaluate) {
        return toAjax(infoProjectEvaluateService.insertInfoProjectEvaluate(infoProjectEvaluate));
    }

    /**
     * 修改项目评价
     */
    @PreAuthorize("@ss.hasPermi('infoProjectEvaluate:infoProjectEvaluate:edit')")
    @Log(title = "项目评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoProjectEvaluate infoProjectEvaluate) {
        return toAjax(infoProjectEvaluateService.updateInfoProjectEvaluate(infoProjectEvaluate));
    }

    /**
     * 删除项目评价
     */
    @PreAuthorize("@ss.hasPermi('infoProjectEvaluate:infoProjectEvaluate:remove')")
    @Log(title = "项目评价", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(infoProjectEvaluateService.deleteInfoProjectEvaluateByIds(ids));
    }

    /**
     * 修改评价审核状态
     * 下达 @ evaluateId 主数据Id examineStatus 审核状态 0 待下达 1 待填报 2 待审核 3 通过 4 已退回
     * <p>
     * 审核 @ evaluateId 主数据Id ； examineStatus 审核状态 0 待下达 1 待填报 2 待审核 3 通过 4 已退回 ；  examineRemarks 总体审核意见
     *
     * @return
     */
    @RequestMapping(value = "/editExamineEvaluate", method = RequestMethod.POST)
    public AjaxResult editExamineEvaluate(@RequestBody ProjectEvaluateExamineVo projectEvaluateExamineVo) {
        return toAjax(infoProjectEvaluateService.editExamineEvaluate(projectEvaluateExamineVo));
    }

    /**
     * 获取项目自评的详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getProjectEvaluateDetail/{id}", method = RequestMethod.GET)
    public AjaxResult getProjectEvaluateDetail(@PathVariable("id") Long id) {
        ProjectEvaluateDetailVo detailVo = infoProjectEvaluateService.getProjectEvaluateDetail(id);
        return AjaxResult.success(detailVo);
    }


    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 项目评价报告下载
     */
    @PostMapping("/download/{id}")
    @ResponseBody
    public AjaxResult download(@PathVariable("id") Long id) {
        String fileName = null;
        InfoProjectEvaluate infoProjectEvaluate = infoProjectEvaluateService.selectInfoProjectEvaluateById(id);
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoProjectEvaluateController.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("zj.ftl", "utf-8");
            Map<String, Object> data = new HashMap<>();
            data.put("projectEvaluate", infoProjectEvaluate);

            InfoProjectEvaluateIndex projectEvaluateIndex = new InfoProjectEvaluateIndex();
            projectEvaluateIndex.setProjectEvaluateId(infoProjectEvaluate.getId());
            List<InfoProjectEvaluateIndex> infoProjectEvaluateIndices = infoProjectEvaluateIndexService.selectInfoProjectEvaluateIndexList(projectEvaluateIndex);
            double zongfeng = 0;
            double dfs = 0;
            double fz = 0;
            for (int i = 0; i < infoProjectEvaluateIndices.size(); i++) {
                InfoProjectEvaluateIndex projectEvaluateIndex1 = infoProjectEvaluateIndices.get(i);
               /* if (!org.springframework.util.StringUtils.isEmpty(projectEvaluateIndex1.getFinishValue())) {
                    // dfs += Integer.parseInt(target1.getScore());
                      zongfeng += Double.parseDouble(projectEvaluateIndex1.getFinishValue());
                }*/
                if (!org.springframework.util.StringUtils.isEmpty(projectEvaluateIndex1.getItemGetScore())) {
                    // dfs += Integer.parseInt(target1.getScore());
                    dfs += Double.parseDouble(projectEvaluateIndex1.getItemGetScore());
                }
                if (!org.springframework.util.StringUtils.isEmpty(projectEvaluateIndex1.getTargetScore())) {
                    fz += Double.parseDouble(projectEvaluateIndex1.getTargetScore());
                }
            }
            data.put("projectTargets", infoProjectEvaluateIndices);


            //指标描述开始
            List<InfoProjectEvaluateIndex> ipe =infoProjectEvaluateIndices.stream().collect(
                    collectingAndThen(
                            toCollection(() -> new TreeSet<>(Comparator.comparing(InfoProjectEvaluateIndex::getTargetOne))), ArrayList::new)
            );
            System.out.println(JSONObject.toJSONString(ipe));
            for(InfoProjectEvaluateIndex index:ipe){
               List<InfoProjectEvaluateIndex>  two=infoProjectEvaluateIndices.stream()
                       .filter(item -> item.getTargetOne().equals(index.getTargetOne()))
                       .filter(distinctByKey(InfoProjectEvaluateIndex::getTargetTwo)).collect(Collectors.toList());
                System.out.println(JSONObject.toJSONString(two));
                index.setTargetTwoList(two);
                for(InfoProjectEvaluateIndex indexThree:two){
                    List<InfoProjectEvaluateIndex>  three =infoProjectEvaluateIndices.stream()
                            .filter(item -> item.getTargetOne().equals(index.getTargetOne()) && item.getTargetTwo().equals(indexThree.getTargetTwo())).collect(Collectors.toList());
                    indexThree.setTargetThreeList(three);
                }
            }
            System.out.println(JSONObject.toJSONString(ipe));
            data.put("projectTargetList", ipe);
            //指标描述结束
            fileName = infoProjectEvaluate.getProjectName();

            BigDecimal totalrate = infoProjectEvaluate.getTotalFundsRate().scaleByPowerOfTen(2);
            BigDecimal cenrate = infoProjectEvaluate.getCentralFundRate().scaleByPowerOfTen(2);
            BigDecimal prorate = infoProjectEvaluate.getProvincialFundsRate().scaleByPowerOfTen(2);
            BigDecimal otherrate = infoProjectEvaluate.getOtherFundRate().scaleByPowerOfTen(2);
            infoProjectEvaluate.setTotalFundsRate(totalrate);
            infoProjectEvaluate.setCentralFundRate(cenrate);
            infoProjectEvaluate.setProvincialFundsRate(prorate);
            infoProjectEvaluate.setOtherFundRate(otherrate);

            data.put("project", infoProjectEvaluate);
            //data.put("zongfeng", zongfeng);
            data.put("dfs", dfs);
            data.put("fz", fz);

            Writer out = null;

            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + "项目自评价报告" + ".doc");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);
            out.close();
            System.out.println("................word文档生成成功 !.............");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(infoProjectEvaluate.getProjectName() + "项目自评价报告" + ".doc");
    }

    /**
     * 上传文件
     */
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public AjaxResult uploadFiles(@RequestBody InfoProjectEvaluate infoProjectEvaluate) {
        return toAjax(infoProjectEvaluateService.uploadFiles(infoProjectEvaluate));
    }
}
